/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/11/25 09:30
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

(function () {
    "use strict";

    var api = {
        getCashMealListUrl: '/money/cashinsets/getMeals',
        doEditUrl: '/money/cashinsets/doEdit',
        doAddUrl: '/money/cashinsets/doAdd',
        doChangeStatusUrl: '/money/cashinsets/changeStatus'
    };
    sm.controller('admin-cashin-sets-controller', ['$scope', '$http', 'Modal', function ($scope, $http, Modal) {

        $scope.meals = [];
        $scope.item = {};
        $scope.total = 0;
        $scope.nextPage = false;
        $scope.type = 'add';
        $scope.index = 0;
        $scope.error = {
            show: false,
            msg: ''
        };

        $scope.getMeals = function () {
            $http.get(api.getCashMealListUrl, {
                params: {
                    page: 1
                }
            }).success(function (res) {
                if (res.state) {
                    $scope.meals = res.data.data;
                    $scope.total = res.data.total;
                    $scope.nextPage = res.data.nextPage;
                }
            });
        };

        $scope.getMeals();

        // add
        $scope.showAddModal = function () {
            $scope.type = 'add';
            $scope.item = {};
            $scope.error = {
                show: false,
                msg: ""
            };
            $('#cashModal').modal();
        };

        // edit
        $scope.edit = function(item) {
            $scope.type = 'edit';
            $scope.index = $scope.meals.indexOf(item); // 下标
            $scope.error = {
                show: false,
                msg: ""
            };
            $scope.item = item;
            $scope.item.amount_yun = parseFloat(item['amount'] / 100);
            // 打开模态框
            $('#cashModal').modal();
        };

        $scope.remove = function (item) {
            var index = $scope.meals.indexOf(item);
            if (item.status < 0) {
                return false;
            }

            Modal.alert({
                title: '确认删除此套餐？',
                content: '删除套餐有可能',
                buttons: [{
                    name: '取消',
                    type: 'cancel'
                }, {
                    name: '确认删除',
                    event: function () {
                        doChangeStatus(item, 'remove');
                    }
                }]
            });
        };

        /**
         * 修改状态
         * @param item
         */
        $scope.changeStatus = function(item) {
            var nowStatus = item.status;
            var newStatus = '';
            if (nowStatus == 5) {
                newStatus = 'on'
            } else if (nowStatus == 6) {
                newStatus = 'off'
            }

            doChangeStatus(item, newStatus);

        };

        function doChangeStatus(item, newStatus) {
            var index = $scope.meals.indexOf(item);
            $http.post(api.doChangeStatusUrl, {
                id: item.id,
                status: newStatus
            }).success(function (res) {
                var str = newStatus == 'on' || newStatus == 'off' ? '修改' : '删除';
                if (res.state) {
                    if (newStatus == 'remove') {
                        $scope.meals.splice(index, 1);
                    } else {
                        Modal.alert({title: str + '成功'});
                        $scope.meals[index].status = newStatus == 'on' ? 6 : 5;
                    }
                } else {
                    Modal.error({title: str + '失败'});
                }
            });
        }


        // submit
        $scope.submit = function() {

            var amount = parseInt($scope.item.amount_yun * 100);
            if (amount < 0 || !amount) {
                $scope.error = {
                    show: true,
                    msg: '请输入正确的套餐金额,单位（元）'
                };
                return false;
            }

            var data = {
                'name': $scope.item.name,
                'description': $scope.item.description,
                'amount': amount
            };

            if ($scope.type == 'add') {
                // 添加
                doSubmit(data, 'add');
            } else {
                // 编辑
                data['id'] = $scope.item.id;
                doSubmit(data, 'edit');
            }
        };

        // 提交
        function doSubmit(data, type) {
            var url;
            if (type == 'add') {
                url = api.doAddUrl;
            } else {
                url = api.doEditUrl;
            }

            $http.post(url, data).success(function (res) {
                if (res.state) {
                    // 成功
                    if (type == 'add') {
                        $scope.meals.unshift(res.data);
                    } else {
                        var index = $scope.index;
                        $scope.meals[index]['name'] = data.name;
                        $scope.meals[index]['description'] = data.description;
                        $scope.meals[index]['amount'] = data.amount;
                        $scope.meals[index]['amount_format'] = parseFloat(data.amount / 100).toFixed(2);
                    }
                    hideModal();
                } else {
                    // 失败
                    var str = type == 'add' ? '添加' : '编辑';
                    var err = res.error || str + '失败';
                    $scope.error = {
                        show: true,
                        msg: err
                    };
                }
            });
        }

        function hideModal()
        {
            setTimeout(function () {
                $('#cashModal').modal('hide');
            });
        }

    }]);

})();

